<?php
// 1. 读取数据库配置
$keyfile = __DIR__ . '/key/key.txt';
if (file_exists($keyfile)) {
    $lines = file($keyfile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $db_name = isset($lines[0]) ? trim($lines[0]) : '';
    $db_user = isset($lines[1]) ? trim($lines[1]) : '';
    $db_pass = isset($lines[2]) ? trim($lines[2]) : '';
} else {
    die('数据库配置文件不存在！');
}

// 2. 连接数据库
$mysqli = new mysqli('localhost', $db_user, $db_pass, $db_name);
if ($mysqli->connect_errno) {
    die('数据库连接失败: ' . $mysqli->connect_error);
}
$mysqli->set_charset('utf8mb4');

// 3. 建表（只建一次）
$mysqli->query("CREATE TABLE IF NOT EXISTS liuyan (
    id INT AUTO_INCREMENT PRIMARY KEY,
    nickname VARCHAR(50) NOT NULL,
    content TEXT NOT NULL,
    ip VARCHAR(45) NOT NULL,
    time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

// 百度API配置：从文件读取access_token
$baidu_token_file = __DIR__ . '/key/baidu_api_token.txt';
if (file_exists($baidu_token_file)) {
    $baidu_api_token = trim(file($baidu_token_file)[0]);
} else {
    die('百度API Token文件不存在！');
}
$baidu_api_url = 'https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=' . $baidu_api_token;

// 获取用户真实IP
function getUserIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ipList = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        return trim($ipList[0]);
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

/**
 * 发起http post请求(REST API), 并获取REST请求的结果
 * @param string $url
 * @param string $param
 * @return - http response body if succeeds, else false.
 */
function request_post($url = '', $param = '')
{
    if (empty($url) || empty($param)) {
        return false;
    }

    $postUrl = $url;
    $curlPost = $param;
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $postUrl);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($curl);
    curl_close($curl);

    return $data;
}

/**
 * 审核文本内容
 * @param string $text 要审核的文本
 * @return array|false 审核结果数组，失败返回false
 */
function censorText($text) {
    global $baidu_api_url;
    $bodys = array(
        'text' => $text
    );
    $res = request_post($baidu_api_url, $bodys);
    if ($res) {
        return json_decode($res, true);
    }
    return false;
}

// 4. 处理留言提交
$err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nickname = trim($_POST['nickname'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $ip = getUserIP();

    if ($nickname === '' || $content === '') {
        $err = '昵称和留言内容不能为空！';
    } else if (mb_strlen($nickname) > 50) {
        $err = '昵称太长啦！';
    } else {
        // 限制同一IP两分钟内只能留言一次
        $stmt = $mysqli->prepare("SELECT time FROM liuyan WHERE ip = ? ORDER BY time DESC LIMIT 1");
        $stmt->bind_param('s', $ip);
        $stmt->execute();
        $stmt->bind_result($last_time);
        $stmt->fetch();
        $stmt->close();

        if ($last_time) {
            $last_timestamp = strtotime($last_time);
            if (time() - $last_timestamp < 120) {
                $err = '发送过于频繁，请两分钟后再试。';
            }
        }

        // 先审核昵称
        if (empty($err)) {
            $nickname_result = censorText($nickname);
            if ($nickname_result && isset($nickname_result['conclusionType'])) {
                if ($nickname_result['conclusionType'] != 1) {
                    $err = '昵称内容不合规，请修改后重试！';
                }
            }
        }

        // 如果没有昵称错误，再审核内容
        if (empty($err)) {
            $content_result = censorText($content);
            if ($content_result && isset($content_result['conclusionType'])) {
                if ($content_result['conclusionType'] != 1) {
                    $err = '留言内容不合规，请修改后重试！';
                }
            }
        }

        // 如果都没有问题，则存入数据库
        if (empty($err)) {
            $stmt = $mysqli->prepare("INSERT INTO liuyan (nickname, content, ip) VALUES (?, ?, ?)");
            $stmt->bind_param('sss', $nickname, $content, $ip);
            $stmt->execute();
            $stmt->close();
            header("Location: ".$_SERVER['PHP_SELF']);
            exit;
        }
    }
}

// 5. 获取所有留言
$res = $mysqli->query("SELECT nickname, content, time FROM liuyan ORDER BY id DESC LIMIT 100");
$messages = [];
while ($row = $res->fetch_assoc()) {
    $messages[] = $row;
}
$res->free();
$mysqli->close();
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>凌红留言墙</title>
    <style>
        :root { --primary-red: #b71c1c; --primary-yellow: #ffd600; }
        body { margin: 0; font-family: 'Microsoft YaHei', sans-serif; background: linear-gradient(45deg, #fff3e0, #ffebee); }
        .container { max-width: 900px; margin: 0 auto; padding: 20px; }
        nav { background: var(--primary-red); padding: 1rem; border-radius: 15px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        nav ul { display: flex; justify-content: center; list-style: none; padding: 0; margin: 0; }
        nav li { margin: 0 20px; }
        nav a { color: white; text-decoration: none; font-size: 1.2rem; padding: 10px 20px; border-radius: 25px; transition: all 0.3s; }
        nav a:hover { background: var(--primary-yellow); color: var(--primary-red); }
        .title { background: linear-gradient(45deg, var(--primary-red), #d32f2f); color: white; padding: 2rem 0; margin: 2rem 0 1.5rem 0; border-radius: 20px; text-align: center; font-size: 2.2rem;}
        .subtitle {font-weight: bold; color: #c62828; text-align: center; margin-bottom: 1.2em; font-size: 1.1em;}
        .msg-board { background: #fff; border-radius: 16px; box-shadow: 0 4px 6px rgba(0,0,0,0.07); padding: 2rem; min-height: 200px; margin-bottom: 2rem;}
        .msg-item { border-bottom: 1px solid #eee; padding: 0.5rem 0; }
        .msg-item:last-child { border-bottom: none; }
        .msg-nick { color: var(--primary-red); font-weight: bold; }
        .msg-time { color: #aaa; font-size: 0.95rem; margin-left: 1em;}
        .msg-content { margin: 0.3em 0 0.7em 0; font-size: 1.1em;}
        .msg-form { background: #fffde7; border-radius: 16px; box-shadow: 0 2px 4px rgba(0,0,0,0.06); padding: 2rem; }
        .msg-form label { display: block; margin-bottom: 0.5em; color: var(--primary-red);}
        .msg-form input[type="text"], .msg-form textarea {
            width: 100%; font-size: 1.1em; padding: 0.7em; margin-bottom: 1em; border: 1px solid #ccc; border-radius: 8px; box-sizing: border-box; resize: none;
        }
        .msg-form button {
            background: var(--primary-red); color: #fff; border: none; border-radius: 8px; font-size: 1.1em; padding: 0.7em 2em; cursor: pointer; transition: background 0.2s;
        }
        .msg-form button:hover { background: var(--primary-yellow); color: var(--primary-red); }
        .msg-err { color: #e53935; margin-bottom: 1em; font-weight: bold;}
        footer { background: var(--primary-red); color: white; text-align: center; padding: 1rem; border-radius: 15px; margin-top: 2rem; }
        .copyright-link {color: #ffd600; text-decoration: underline;}
        @media (max-width: 768px) {
            nav ul { flex-direction: column; }
            nav li { margin: 10px 0; }
            .container { padding: 5px;}
            .title { font-size: 1.3rem;}
        }
    </style>
</head>
<body>
    <nav>
        <ul>
            <li><a href="index.html">首页</a></li>
            <li><a href="page2.html">页面2</a></li>
            <li><a href="page3.html">页面3</a></li>
            <li><a href="page4.html">页面4</a></li>
            <li><a href="page5.html">页面5</a></li>
            <li><a href="liuyan.php">留言墙</a></li>
        </ul>
    </nav>
    <div class="container">
        <div class="title">凌红留言墙</div>
        <div class="subtitle">本站禁止发送一切涉及黄赌毒等违法留言。</div>
        <div class="msg-board">
            <?php if (empty($messages)): ?>
                <div style="color:#aaa;text-align:center;">暂无留言，快来抢沙发！</div>
            <?php else: ?>
                <?php foreach ($messages as $msg): ?>
                    <div class="msg-item">
                        <span class="msg-nick"><?php echo htmlspecialchars($msg['nickname']); ?></span>
                        <span class="msg-time"><?php echo htmlspecialchars($msg['time']); ?></span>
                        <div class="msg-content"><?php echo nl2br(htmlspecialchars($msg['content'])); ?></div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        <div class="msg-form">
            <?php if ($err): ?><div class="msg-err"><?php echo $err; ?></div><?php endif; ?>
            <form method="post" autocomplete="off">
                <label for="nickname">留言者昵称：</label>
                <input type="text" id="nickname" name="nickname" maxlength="50" required>
                <label for="content">留言内容：</label>
                <textarea id="content" name="content" rows="4" maxlength="500" required></textarea>
                <button type="submit">发送</button>
            </form>
        </div>
    </div>
    <footer>
        <p>本页面基于
            <a href="https://gitee.com/guozhufeng/linghong-message-wall" target="_blank" class="copyright-link">凌红留言墙</a>
            开发
        </p>
    </footer>
</body>
</html>
